#!/bin/sh /etc/rc.common

USE_PROCD=1

START=99
STOP=15

NAME=aliyundrive-webdav

uci_get_by_type() {
	local ret=$(uci get $NAME.@$1[0].$2 2>/dev/null)
	echo ${ret:=$3}
}

start_service() {
  local enable=$(uci_get_by_type server enable)
  case "$enable" in
    1|on|true|yes|enabled)
      local refresh_token=$(uci_get_by_type server refresh_token)
      local auth_user=$(uci_get_by_type server auth_user)
      local auth_password=$(uci_get_by_type server auth_password)
      local read_buf_size=$(uci_get_by_type server read_buffer_size 10485760)
      local cache_size=$(uci_get_by_type server cache_size 1000)
      local cache_ttl=$(uci_get_by_type server cache_ttl 600)
      local host=$(uci_get_by_type server host 127.0.0.1)
      local port=$(uci_get_by_type server port 8080)
      local root=$(uci_get_by_type server root /)
      local domain_id=$(uci_get_by_type server domain_id)

      local extra_options="-I"

      if [[ ! -z "$domain_id" ]]; then
        extra_options="$extra_options --domain-id $domain_id"
      else
        case "$(uci_get_by_type server no_trash 0)" in
          1|on|true|yes|enabled)
            extra_options="$extra_options --no-trash"
            ;;
          *) ;;
        esac

        case "$(uci_get_by_type server read_only 0)" in
          1|on|true|yes|enabled)
            extra_options="$extra_options --read-only"
            ;;
          *) ;;
        esac
      fi

      procd_open_instance
      procd_set_param command /bin/sh -c "/usr/bin/$NAME $extra_options --host $host --port $port --root $root -S $read_buf_size --cache-size $cache_size --cache-ttl $cache_ttl --workdir /var/run/$NAME >>/var/log/$NAME.log 2>&1"
      procd_set_param pidfile /var/run/$NAME.pid
      procd_set_param env REFRESH_TOKEN="$refresh_token"
      [[ ! -z "$auth_user" ]] && procd_append_param env WEBDAV_AUTH_USER="$auth_user"
      [[ ! -z "$auth_password" ]] && procd_append_param env WEBDAV_AUTH_PASSWORD="$auth_password"
      case $(uci_get_by_type server debug) in
        1|on|true|yes|enabled)
          procd_append_param env RUST_LOG="aliyundrive_webdav=debug" ;;
        *) ;;
      esac
      procd_close_instance ;;
    *)
      stop_service ;;
  esac
}

service_triggers() {
	procd_add_reload_trigger "aliyundrive-webdav"
}
